import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Button,
  Upload,
  Table,
  Space,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
  Tag,
  Progress,
  Tooltip,
  Breadcrumb,
  Row,
  Col,
  Statistic,
  List,
  Avatar,
  Typography,
  Divider,
  Empty,
  Spin,
  Radio,
  DatePicker,
  App
} from 'antd';
import {
  UploadOutlined,
  FolderOutlined,
  FileOutlined,
  DownloadOutlined,
  DeleteOutlined,
  EditOutlined,
  ShareAltOutlined,
  FolderAddOutlined,
  ReloadOutlined,
  HomeOutlined,
  MoreOutlined
} from '@ant-design/icons';
import { cloudStorageService } from '../services/api';
import { FileItem, FolderItem, StorageStats, ShareLinkResponse } from '../types/api';
import type { UploadProps } from 'antd';

const { Title, Text } = Typography;
const { Search } = Input;

const CloudStorage: React.FC = () => {
  const [files, setFiles] = useState<FileItem[]>([]);
  const [folders, setFolders] = useState<FolderItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [currentFolder, setCurrentFolder] = useState<number | null>(null);
  const [breadcrumb, setBreadcrumb] = useState<Array<{id: number, name: string}>>([]);
  const [stats, setStats] = useState<StorageStats | null>(null);
  const [selectedFiles, setSelectedFiles] = useState<number[]>([]);
  const [searchText, setSearchText] = useState('');
  const [allFiles, setAllFiles] = useState<FileItem[]>([]);
  const [allFolders, setAllFolders] = useState<FolderItem[]>([]);
  
  // 模态框状态
  const [createFolderVisible, setCreateFolderVisible] = useState(false);
  const [renameFileVisible, setRenameFileVisible] = useState(false);
  const [renameFolderVisible, setRenameFolderVisible] = useState(false);
  const [shareVisible, setShareVisible] = useState(false);
  const [renameFileId, setRenameFileId] = useState<number | null>(null);
  const [renameFolderId, setRenameFolderId] = useState<number | null>(null);
  const [shareFileId, setShareFileId] = useState<number | null>(null);
  
  const [form] = Form.useForm();
  const [renameForm] = Form.useForm();
  const [shareForm] = Form.useForm();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { modal } = App.useApp();

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      console.log('开始加载云盘数据...');
      console.log('当前文件夹ID:', currentFolder);
      
      const [filesRes, foldersRes, statsRes] = await Promise.all([
        cloudStorageService.getFiles(currentFolder || undefined, 1, 100),
        cloudStorageService.getFolders(currentFolder || undefined),
        cloudStorageService.getStats()
      ]);

      console.log('API响应结果:');
      console.log('文件列表:', filesRes);
      console.log('文件夹列表:', foldersRes);
      console.log('统计信息:', statsRes);

      if (filesRes.success) {
        const filesData = filesRes.files || [];
        setFiles(filesData);
        setAllFiles(filesData);
        console.log('✅ 设置文件列表:', filesData.length, '个文件');
      } else {
        console.error('❌ 获取文件列表失败:', filesRes);
      }
      
      if (foldersRes.success) {
        const foldersData = foldersRes.folders || [];
        setFolders(foldersData);
        setAllFolders(foldersData);
        console.log('✅ 设置文件夹列表:', foldersData.length, '个文件夹');
      } else {
        console.error('❌ 获取文件夹列表失败:', foldersRes);
      }
      
      if (statsRes.success) {
        setStats(statsRes);
        console.log('✅ 设置统计信息:', statsRes);
      } else {
        console.error('❌ 获取统计信息失败:', statsRes);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败: ' + (error as any).message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [currentFolder]);

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取文件图标
  const getFileIcon = (mimeType: string) => {
    if (mimeType.startsWith('image/')) return '🖼️';
    if (mimeType.startsWith('video/')) return '🎥';
    if (mimeType.startsWith('audio/')) return '🎵';
    if (mimeType.includes('pdf')) return '📄';
    if (mimeType.includes('word')) return '📝';
    if (mimeType.includes('excel')) return '📊';
    if (mimeType.includes('powerpoint')) return '📈';
    if (mimeType.includes('zip') || mimeType.includes('rar')) return '📦';
    return '📄';
  };

  // 上传文件
  const handleUpload = async (file: File) => {
    console.log('开始上传文件:', file.name, '类型:', file.type, '大小:', file.size);
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('files', file);
      if (currentFolder) {
        formData.append('folderId', currentFolder.toString());
      }

      console.log('发送上传请求...');
      console.log('FormData内容:', Array.from(formData.entries()));
      
      const response = await cloudStorageService.uploadFile(formData);
      console.log('上传响应:', response);
      
      if (response.success) {
        message.success('文件上传成功');
        loadData();
      } else {
        console.error('上传失败:', response.message);
        message.error(response.message || '上传失败');
      }
    } catch (error) {
      console.error('上传异常:', error);
      console.error('错误详情:', {
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        response: (error as any)?.response?.data,
        status: (error as any)?.response?.status
      });
      message.error(`上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setUploading(false);
    }
  };

  // 创建文件夹
  const handleCreateFolder = async (values: { folderName: string }) => {
    try {
      console.log('开始创建文件夹:', values);
      const response = await cloudStorageService.createFolder(
        values.folderName,
        currentFolder || undefined
      );
      console.log('创建文件夹响应:', response);
      if (response.success) {
        message.success('文件夹创建成功');
        setCreateFolderVisible(false);
        form.resetFields();
        loadData();
      } else {
        console.error('创建文件夹失败:', response.message);
        message.error(response.message || '创建失败');
      }
    } catch (error) {
      console.error('创建文件夹异常:', error);
      message.error('创建失败: ' + (error as any).message);
    }
  };

  // 进入文件夹
  const enterFolder = (folderId: number, folderName: string) => {
    setCurrentFolder(folderId);
    setBreadcrumb(prev => [...prev, { id: folderId, name: folderName }]);
  };

  // 重命名文件夹
  const handleRenameFolder = async (values: { folderName: string }) => {
    if (!renameFolderId) return;
    
    try {
      console.log('开始重命名文件夹:', renameFolderId, values);
      const response = await cloudStorageService.renameFolder(renameFolderId, values.folderName);
      console.log('重命名文件夹响应:', response);
      
      if (response.success) {
        message.success('文件夹重命名成功');
        setRenameFolderVisible(false);
        setRenameFolderId(null);
        renameForm.resetFields();
        loadData();
      } else {
        console.error('重命名文件夹失败:', response.message);
        message.error(response.message || '重命名失败');
      }
    } catch (error) {
      console.error('重命名文件夹异常:', error);
      message.error('重命名失败: ' + (error as any).message);
    }
  };

  // 删除文件夹
  const handleDeleteFolder = async (folderId: number) => {
    try {
      console.log('开始删除文件夹:', folderId);
      const response = await cloudStorageService.deleteFolder(folderId);
      console.log('删除文件夹响应:', response);
      
      if (response.success) {
        message.success('文件夹删除成功');
        loadData();
      } else {
        console.error('删除文件夹失败:', response.message);
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除文件夹异常:', error);
      message.error('删除失败: ' + (error as any).message);
    }
  };

  // 打开重命名文件夹对话框
  const openRenameFolder = (folderId: number, currentName: string) => {
    setRenameFolderId(folderId);
    renameForm.setFieldsValue({ folderName: currentName });
    setRenameFolderVisible(true);
  };

  // 返回上级文件夹
  const goBack = () => {
    if (breadcrumb.length > 0) {
      const newBreadcrumb = [...breadcrumb];
      newBreadcrumb.pop();
      setBreadcrumb(newBreadcrumb);
      setCurrentFolder(newBreadcrumb.length > 0 ? newBreadcrumb[newBreadcrumb.length - 1].id : null);
    }
  };

  // 返回根目录
  const goToRoot = () => {
    setCurrentFolder(null);
    setBreadcrumb([]);
  };

  // 删除文件
  const handleDeleteFile = async (fileId: number) => {
    try {
      const response = await cloudStorageService.deleteFile(fileId);
      if (response.success) {
        message.success('文件删除成功');
        loadData();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 重命名文件
  const handleRenameFile = async (values: { newName: string }) => {
    if (!renameFileId) return;
    
    try {
      const response = await cloudStorageService.renameFile(renameFileId, values.newName);
      if (response.success) {
        message.success('重命名成功');
        setRenameFileVisible(false);
        setRenameFileId(null);
        form.resetFields();
        loadData();
      } else {
        message.error(response.message || '重命名失败');
      }
    } catch (error) {
      message.error('重命名失败');
    }
  };

  // 下载文件
  const handleDownloadFile = async (fileId: number, fileName: string) => {
    try {
      console.log('开始下载文件:', fileId, fileName);
      const response = await cloudStorageService.downloadFile(fileId);
      
      console.log('下载响应:', response);
      
      // 检查响应是否为blob
      if (response instanceof Blob) {
        const url = window.URL.createObjectURL(response);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('文件下载成功');
      } else if (response.data instanceof Blob) {
        const url = window.URL.createObjectURL(response.data);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('文件下载成功');
      } else {
        console.error('下载响应格式错误:', response);
        message.error('下载响应格式错误');
      }
    } catch (error) {
      console.error('下载失败:', error);
      message.error('文件下载失败: ' + (error as any).message);
    }
  };

  // 创建分享链接
  const handleCreateShare = async (values: any): Promise<void> => {
    if (!shareFileId) return;
    
    try {
      console.log('🔗 前端开始创建分享链接...');
      console.log('📋 表单数据:', values);
      
      // 根据用户选择决定分享类型
      const shareType = values.needPassword === 'yes' ? 'password' : 'public';
      const password = values.needPassword === 'yes' ? values.password : null;
      
      // 格式化日期
      const expiresAt = values.expiresAt ? values.expiresAt.format('YYYY-MM-DD HH:mm:ss') : null;
      
      console.log('📤 发送API请求:', {
        fileId: shareFileId,
        shareType,
        hasPassword: !!password,
        expiresAt: expiresAt || '永不过期'
      });
      
      const response = await cloudStorageService.createShare(
        shareFileId,
        shareType,
        password,
        expiresAt
      ) as ShareLinkResponse;
      
      console.log('📥 分享创建响应:', response);
      
      if (response.success) {
        // 显示分享链接
        const shareUrl = response.shareUrl || `${window.location.origin}/share/${response.shareToken}`;
        
        console.log('🎉 分享链接创建成功!');
        console.log('🔗 分享链接:', shareUrl);
        console.log('🎫 分享令牌:', response.shareToken);
        
        modal.success({
          title: '分享链接创建成功',
          content: (
            <div>
              <p>分享链接已创建，您可以复制以下链接分享给其他人：</p>
              <Input.TextArea
                value={shareUrl}
                readOnly
                rows={3}
                style={{ marginTop: 10 }}
              />
              <div style={{ marginTop: 10 }}>
                <Button
                  type="primary"
                  onClick={() => {
                    console.log('📋 复制分享链接到剪贴板:', shareUrl);
                    navigator.clipboard.writeText(shareUrl);
                    message.success('链接已复制到剪贴板');
                  }}
                >
                  复制链接
                </Button>
              </div>
            </div>
          ),
          onOk: () => {
            console.log('✅ 用户确认分享链接，关闭模态框');
            setShareVisible(false);
            setShareFileId(null);
            shareForm.resetFields();
            loadData();
          }
        });
      } else {
        console.error('❌ 分享链接创建失败:', response);
        message.error(response.message || response.error || '创建分享失败');
      }
    } catch (error) {
      console.error('❌ 创建分享异常:', error);
      console.error('📋 错误详情:', {
        message: (error as any).message,
        stack: (error as any).stack
      });
      message.error('创建分享失败: ' + (error as any).message);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '名称',
      dataIndex: 'file_name',
      key: 'name',
      render: (text: string, record: FileItem) => (
        <Space>
          <span style={{ fontSize: '16px' }}>
            {getFileIcon(record.mime_type)}
          </span>
          <Text strong>{text}</Text>
          {record.is_shared === true && <Tag color="blue">已分享</Tag>}
        </Space>
      ),
    },
    {
      title: '大小',
      dataIndex: 'file_size',
      key: 'size',
      render: (size: number) => formatFileSize(size),
      width: 100,
    },
    {
      title: '下载次数',
      dataIndex: 'download_count',
      key: 'downloads',
      width: 100,
    },
    {
      title: '上传时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleString(),
      width: 150,
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: FileItem) => (
        <Space>
          <Tooltip title="下载">
            <Button
              type="text"
              icon={<DownloadOutlined />}
              onClick={() => handleDownloadFile(record.id, record.file_name)}
            />
          </Tooltip>
          <Tooltip title="重命名">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => {
                setRenameFileId(record.id);
                setRenameFileVisible(true);
                form.setFieldsValue({ newName: record.file_name });
              }}
            />
          </Tooltip>
          <Tooltip title="分享">
            <Button
              type="text"
              icon={<ShareAltOutlined />}
              onClick={() => {
                console.log('🔗 用户点击分享按钮:', {
                  fileId: record.id,
                  fileName: record.file_name,
                  fileSize: record.file_size
                });
                setShareFileId(record.id);
                setShareVisible(true);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个文件吗？"
            onConfirm={() => handleDeleteFile(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
      width: 150,
    },
  ];

  return (
    <div style={{ padding: '16px', background: '#f5f5f5', minHeight: 'auto', overflow: 'hidden' }}>
      <Row gutter={[16, 16]}>
        {/* 左侧统计信息 */}
        <Col span={6}>
          <Card title="存储统计" style={{ marginBottom: 16 }}>
            {stats && (
              <>
                <Statistic
                  title="已使用空间"
                  value={stats.quota.used_quota}
                  formatter={(value) => formatFileSize(Number(value))}
                />
                <Progress
                  percent={Math.round((stats.quota.used_quota / stats.quota.total_quota) * 100)}
                  status={stats.quota.used_quota / stats.quota.total_quota > 0.9 ? 'exception' : 'normal'}
                />
                <Divider />
                <Row gutter={16}>
                  <Col span={12}>
                    <Statistic title="文件数量" value={stats.quota.file_count} />
                  </Col>
                  <Col span={12}>
                    <Statistic title="文件夹数量" value={stats.quota.folder_count} />
                  </Col>
                </Row>
              </>
            )}
          </Card>

          <Card title="最近文件" size="small">
            {stats?.recentFiles && stats.recentFiles.length > 0 ? (
              <List
                dataSource={stats.recentFiles}
                renderItem={(file) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<Avatar icon={<FileOutlined />} />}
                      title={file.file_name}
                      description={formatFileSize(file.file_size)}
                    />
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无最近文件" />
            )}
          </Card>
        </Col>

        {/* 右侧主要内容 */}
        <Col span={18}>
          <Card>
            {/* 工具栏 */}
            <div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Space>
                <Button
                  type="primary"
                  icon={<UploadOutlined />}
                  onClick={() => fileInputRef.current?.click()}
                  loading={uploading}
                >
                  上传文件
                </Button>
                <Button
                  icon={<FolderAddOutlined />}
                  onClick={() => setCreateFolderVisible(true)}
                >
                  新建文件夹
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={loadData}
                >
                  刷新
                </Button>
              </Space>

              <Search
                placeholder="搜索文件或文件夹"
                value={searchText}
                onChange={(e) => {
                  const value = e.target.value;
                  setSearchText(value);
                  
                  if (value.trim() === '') {
                    // 清空搜索，显示所有数据
                    setFiles(allFiles);
                    setFolders(allFolders);
                  } else {
                    // 过滤文件列表
                    const filteredFiles = allFiles.filter(file => 
                      file.file_name.toLowerCase().includes(value.toLowerCase())
                    );
                    // 过滤文件夹列表
                    const filteredFolders = allFolders.filter(folder => 
                      folder.folder_name.toLowerCase().includes(value.toLowerCase())
                    );
                    setFiles(filteredFiles);
                    setFolders(filteredFolders);
                  }
                }}
                onSearch={(value) => {
                  if (value.trim() === '') {
                    setFiles(allFiles);
                    setFolders(allFolders);
                  } else {
                    const filteredFiles = allFiles.filter(file => 
                      file.file_name.toLowerCase().includes(value.toLowerCase())
                    );
                    const filteredFolders = allFolders.filter(folder => 
                      folder.folder_name.toLowerCase().includes(value.toLowerCase())
                    );
                    setFiles(filteredFiles);
                    setFolders(filteredFolders);
                  }
                }}
                allowClear
                style={{ width: 200 }}
              />
            </div>

            {/* 面包屑导航 */}
            <Breadcrumb style={{ marginBottom: 12 }}>
              <Breadcrumb.Item>
                <Button type="link" icon={<HomeOutlined />} onClick={goToRoot}>
                  根目录
                </Button>
              </Breadcrumb.Item>
              {breadcrumb.map((item, index) => (
                <Breadcrumb.Item key={item.id}>
                  <Button
                    type="link"
                    onClick={() => {
                      const newBreadcrumb = breadcrumb.slice(0, index + 1);
                      setBreadcrumb(newBreadcrumb);
                      setCurrentFolder(item.id);
                    }}
                  >
                    {item.name}
                  </Button>
                </Breadcrumb.Item>
              ))}
            </Breadcrumb>

            {/* 文件夹列表 */}
            {folders.length > 0 && (
              <div style={{ marginBottom: 12 }}>
                <Title level={5}>文件夹</Title>
                <Row gutter={[16, 16]}>
                  {folders.map((folder) => (
                    <Col span={6} key={folder.id}>
                      <Card
                        hoverable
                        style={{ textAlign: 'center', position: 'relative' }}
                        actions={[
                          <Tooltip title="重命名">
                            <EditOutlined 
                              key="rename"
                              onClick={(e) => {
                                e.stopPropagation();
                                openRenameFolder(folder.id, folder.folder_name);
                              }}
                            />
                          </Tooltip>,
                          <Tooltip title="删除">
                            <Popconfirm
                              title="确定要删除这个文件夹吗？"
                              description="删除后无法恢复，请确保文件夹为空。"
                              onConfirm={(e) => {
                                e?.stopPropagation();
                                handleDeleteFolder(folder.id);
                              }}
                              onCancel={(e) => e?.stopPropagation()}
                              okText="确定"
                              cancelText="取消"
                            >
                              <DeleteOutlined 
                                key="delete"
                                style={{ color: '#ff4d4f' }}
                                onClick={(e) => e.stopPropagation()}
                              />
                            </Popconfirm>
                          </Tooltip>
                        ]}
                        onClick={() => enterFolder(folder.id, folder.folder_name)}
                      >
                        <FolderOutlined style={{ fontSize: '32px', color: '#1890ff' }} />
                        <div style={{ marginTop: 8 }}>
                          <Text strong>{folder.folder_name}</Text>
                        </div>
                      </Card>
                    </Col>
                  ))}
                </Row>
              </div>
            )}

            {/* 文件列表 */}
            <div>
              <Title level={5}>文件</Title>
              <Table
                columns={columns}
                dataSource={files}
                rowKey="id"
                loading={loading}
                pagination={false}
                size="small"
                scroll={{ y: 'auto' }}
                style={{ marginBottom: 0 }}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        style={{ display: 'none' }}
        onChange={(e) => {
          console.log('文件选择事件触发:', e.target.files);
          const file = e.target.files?.[0];
          if (file) {
            console.log('选择的文件:', file.name, file.type, file.size);
            handleUpload(file);
          } else {
            console.log('没有选择文件');
          }
        }}
      />

      {/* 创建文件夹模态框 */}
      <Modal
        title="创建文件夹"
        open={createFolderVisible}
        onCancel={() => {
          setCreateFolderVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} onFinish={handleCreateFolder}>
          <Form.Item
            name="folderName"
            label="文件夹名称"
            rules={[{ required: true, message: '请输入文件夹名称' }]}
          >
            <Input placeholder="请输入文件夹名称" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 重命名文件夹模态框 */}
      <Modal
        title="重命名文件夹"
        open={renameFolderVisible}
        onCancel={() => {
          setRenameFolderVisible(false);
          setRenameFolderId(null);
          renameForm.resetFields();
        }}
        onOk={() => renameForm.submit()}
      >
        <Form form={renameForm} onFinish={handleRenameFolder}>
          <Form.Item
            name="folderName"
            label="文件夹名称"
            rules={[{ required: true, message: '请输入文件夹名称' }]}
          >
            <Input placeholder="请输入新的文件夹名称" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 重命名文件模态框 */}
      <Modal
        title="重命名文件"
        open={renameFileVisible}
        onCancel={() => {
          setRenameFileVisible(false);
          setRenameFileId(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} onFinish={handleRenameFile}>
          <Form.Item
            name="newName"
            label="新文件名"
            rules={[{ required: true, message: '请输入新文件名' }]}
          >
            <Input placeholder="请输入新文件名" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 分享模态框 */}
      <Modal
        title="创建分享链接"
        open={shareVisible}
        onCancel={() => {
          setShareVisible(false);
          setShareFileId(null);
          shareForm.resetFields();
        }}
        onOk={() => shareForm.submit()}
      >
        <Form form={shareForm} onFinish={handleCreateShare}>
          <Form.Item
            name="needPassword"
            label="是否需要密码"
            initialValue="no"
            rules={[{ required: true, message: '请选择是否需要密码' }]}
          >
            <Radio.Group>
              <Radio value="no">不需要密码</Radio>
              <Radio value="yes">需要密码</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.needPassword !== currentValues.needPassword}>
            {({ getFieldValue }) => {
              const needPassword = getFieldValue('needPassword');
              return needPassword === 'yes' ? (
                <Form.Item
                  name="password"
                  label="分享密码"
                  rules={[{ required: true, message: '请输入分享密码' }]}
                >
                  <Input.Password placeholder="请输入分享密码" />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          <Form.Item
            name="expiresAt"
            label="分享截止日期"
          >
            <DatePicker 
              showTime 
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择分享截止日期"
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CloudStorage;